import paramiko
import datetime
import pathlib
import sys
import json
import re
import os


def main(args):
    [local_dir,province,start_date,end_date,remote_dir]=args

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname="192.168.1.82",port=22,username="root",password="000000")
    sftp: paramiko.SFTPClient = client.open_sftp()

    json_path = r"E:\PythonProjcet\RasterShapeToolBox\conf\ChinaMgrs.json"
    with open(json_path, "r", encoding="utf-8") as json_file:
        china_tiles = json.load(json_file)
    tiles = china_tiles[province]
    start_date = datetime.datetime.strptime(start_date,'%Y-%m-%d')
    end_date = datetime.datetime.strptime(end_date,'%Y-%m-%d')

    infos = []
    for tile in tiles:
        temp = start_date
        infos.append(f"{tile}_{temp.strftime('%Y%m%d')}")
        while temp != end_date:
            temp = temp + datetime.timedelta(days=1)
            infos.append(f"{tile}_{temp.strftime('%Y%m%d')}")

    for name in os.listdir(local_dir):
        if re.match("^S2[AB]_MSIL1C_.*\.zip$",name):
            tile = name.split("_")[5][1:]
            date = name.split("_")[2][:8] 
            string = f"{tile}_{date}"
            if string in infos:
                zip_path = os.path.join(local_dir,name)
                result = up_sentinel_zip([zip_path, remote_dir, sftp])   
                print(result)

    sftp.close()
    client.close()      
    return


def up_sentinel_zip(args):
        [zip_path, remote_dir, sftp] = args
        zip_name = os.path.basename(zip_path)
        remote_path = str(pathlib.PurePosixPath(remote_dir, zip_name))
        try:
            stat = sftp.stat(remote_path)
            if stat.st_size != os.path.getsize(zip_path):
                sftp.remove(remote_path)
                try:
                   sftp.chdir(remote_dir)
                except:
                    sftp.mkdir(remote_dir)
                    sftp.chdir(remote_dir)
                    sftp.put(zip_path, remote_path,callback=_Callback,confirm=True)
        except:
            try:
                sftp.chdir(remote_dir)
            except:
                sftp.mkdir(remote_dir)
                sftp.chdir(remote_dir)
            sftp.put(zip_path, remote_path,callback=_Callback,confirm=True) 
        string = f"{datetime.datetime.now().strftime('%H:%M:%S')}:success {zip_name}"
        return string


def _Callback(a=10,b=10):
    percent = round(a*100./int(b),2)
    if  percent in [i for i in range(101)] :
        current_size = round(a/1024./1024,2)
        if percent == 0:
            string = f'{current_size}M {percent}%'
        else:
            string = f'{current_size}M {percent}%'
        sys.stdout.write('\r'+string) 
    return 


if __name__ == "__main__":
    local_dir = r"E:\dataset"
    province = r"河南省"
    start_date = r"2020-12-1"
    end_date = r"2020-12-31"
    remote_dir = r"/83To82/all_data/he_nan/2020_12/1C"
    main([local_dir,province,start_date,end_date,remote_dir])